<template>
  <el-row :gutter="20">
    <!-- 左侧部门树 -->
    <el-col :span="4" :xs="24">
      <ContentWrap class="h-1/1">
        <CategoryTree @node-click="handleCategoryNodeClick" />
      </ContentWrap>
    </el-col>
    <el-col :span="20" :xs="24">
      <ContentWrap>
        <!-- 搜索工作栏 -->
        <el-form
          class="-mb-15px"
          :model="queryParams"
          ref="queryFormRef"
          :inline="true"
          label-width="68px"
        >
          <el-form-item label="物资名称" prop="assetName">
            <el-input
              v-model="queryParams.assetName"
              placeholder="请输入物资名称"
              clearable
              @keyup.enter="handleQuery"
              class="!w-240px"
            />
          </el-form-item>

          <el-form-item v-if="queryParams.oper != 'putin'" label="物资编号" prop="assetCode">
            <el-input
              v-model="queryParams.assetCode"
              placeholder="请输入物资编号"
              clearable
              @keyup.enter="handleQuery"
              class="!w-240px"
            />
          </el-form-item>

          <el-form-item
            v-if="['borrow', 'returns'].includes(queryParams.oper)"
            label="领用人"
            prop="userNames"
          >
            <el-input
              v-model="queryParams.userNames"
              placeholder="请输入领用人"
              clearable
              @keyup.enter="handleQuery"
              class="!w-240px"
            />
          </el-form-item>
          <el-form-item label="创建时间" prop="createTime">
            <el-date-picker
              v-model="queryParams.createTime"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="daterange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
              class="!w-220px"
            />
          </el-form-item>
          <el-form-item>
            <el-button @click="handleQuery"
              ><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button
            >
            <el-button @click="resetQuery"
              ><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button
            >

            <el-button
              type="success"
              plain
              @click="handleExport"
              :loading="exportLoading"
              v-hasPermi="['school:assets-flow:export']"
            >
              <Icon icon="ep:download" class="mr-5px" /> 导出
            </el-button>
          </el-form-item>
        </el-form>
      </ContentWrap>

      <!-- 列表 -->
      <ContentWrap>
        <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
          <!-- <el-table-column label="编号" align="center" prop="id" /> -->
          <!-- <el-table-column label="物资ID" align="center" prop="assetId" /> -->
          <el-table-column label="物资名称" align="center" prop="assetName" />
          <el-table-column
            v-if="queryParams.oper != 'putin'"
            label="物资编号"
            align="center"
            prop="assetCode"
          />
          <el-table-column label="数量" align="center" prop="count" />
          <el-table-column
            v-if="['putin'].includes(queryParams.oper)"
            label="单价（元）"
            align="center"
            prop="price"
          />
          <el-table-column
            v-if="['borrow', 'returns'].includes(queryParams.oper)"
            label="领用人"
            align="center"
            prop="userNames"
          />
          <el-table-column
            v-if="['reputin'].includes(queryParams.oper)"
            label="维修费用（元）"
            align="center"
            prop="price"
          />

          <!-- <el-table-column
            v-if="['fix', 'scrap'].includes(queryParams.oper)"
            label="审批状态"
            align="center"
            prop="bpmStatus"
          >
            <template #default="scope">
              <dict-tag
                :type="DICT_TYPE.BPM_PROCESS_INSTANCE_STATUS"
                :value="scope.row.bpmStatus"
              />
            </template>
          </el-table-column> -->

          <el-table-column label="备注" align="center" prop="remark" />
          <el-table-column
            label="创建时间"
            align="center"
            prop="createTime"
            :formatter="dateFormatter"
            width="180px"
          />

          <!-- <el-table-column label="操作" align="center" min-width="120px">
            <template #default="scope">
              <el-button
                link
                type="primary"
                @click="openForm('update', scope.row.id)"
                v-hasPermi="['school:assets-flow:update']"
              >
                编辑
              </el-button>
              <el-button
                link
                type="danger"
                @click="handleDelete(scope.row.id)"
                v-hasPermi="['school:assets-flow:delete']"
              >
                删除
              </el-button>
            </template>
          </el-table-column> -->
        </el-table>
        <!-- 分页 -->
        <Pagination
          :total="total"
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </ContentWrap>
    </el-col>
  </el-row>
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { AssetsFlowApi, AssetsFlowVO } from '@/api/school/assets/flow'
import CategoryTree from '../fixed/CategoryTree.vue'
import { useRoute } from 'vue-router'
import { getIntDictOptions, getStrDictOptions, DICT_TYPE } from '@/utils/dict'
const route = useRoute()

/** 物资流转 列表 */
defineOptions({ name: 'SchoolAssetsFlow' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<AssetsFlowVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  categoryId: undefined,
  assetType: 0,
  assetId: undefined,
  assetCode: undefined,
  assetName: undefined,
  status: undefined,
  userNames: undefined,
  createTime: [],
  oper: ''
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await AssetsFlowApi.getAssetsFlowPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await AssetsFlowApi.deleteAssetsFlow(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await AssetsFlowApi.exportAssetsFlow(queryParams)
    const fileName = (pathToAssetTypeNameMap[queryParams.oper] || '物资') + `.xlsx`
    download.excel(data, fileName)
  } catch {
  } finally {
    exportLoading.value = false
  }
}
const pathToAssetTypeNameMap = {
  putin: '物资入库记录',
  returns: '物资归还记录',
  borrow: '物资领用记录',
  fix: '物资报修记录',
  scrap: '物资报废记录',
  reputin: '物资重新入库记录'
}

// 路由到 oper 映射关系
const pathToAssetTypeMap = {
  '/asset/fixed/putin': 'putin',
  '/asset/fixed/returns': 'returns',
  '/asset/fixed/borrow': 'borrow',
  '/asset/fixed/fix': 'fix',
  '/asset/fixed/scrap': 'scrap',
  '/asset/fixed/reputin': 'reputin'
  // 可以继续扩展更多路径
}

/** 监听路由，判断是从哪个菜单请求的，然后赋值不同的类型 */
watch(
  () => route.path,
  (path) => {
    console.log(path, '---path')

    // 匹配路径并赋值 assetType，如果没有匹配则设为默认值 0
    queryParams.oper = pathToAssetTypeMap[path] || 0
    console.log(queryParams.oper, '---oper')
  },
  {
    immediate: true //立即执行一次
  }
)

/** 处理分类被点击 */
const handleCategoryNodeClick = async (row) => {
  queryParams.categoryId = row.id
  await getList()
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
